// web/src/app/auth.ts
import NextAuth from "next-auth";
import {authOptions} from "@/auth.config";
import {PrismaAdapter} from "@auth/prisma-adapter";
import {db} from "@/lib/db";
import {getUserById} from "@/data/user";
// import {UserRole} from '@prisma/client'
import {getTwoFactorConfirmationByUserId} from '@/data/two-factor-confirmation'
import {UserRole} from "@/lib/types";
import {getAccountByUserId} from "@/data/account";

export const {
    handlers: {GET, POST},
    // handler,
    auth,
    signIn,
    signOut,
    unstable_update
} = NextAuth({
    // 指定登录页
    pages: {
        signIn: '/auth/login',
        error: '/auth/error'
    },
    events: {
        async linkAccount({user}) {
            // 其他provider登录的时候, 该字段可能缺失
            await db.user.update({
                where: {id: user.id},
                data: {emailVerified: new Date()}
            })
        }
    },
    callbacks: {
        async signIn({user, account}) {
            // 第三方登录不需要邮箱验证
            if (account?.provider !== 'credentials') return true

            // @ts-ignore
            const existingUser = await getUserById(user.id)
            // 没验证邮箱不能登录
            if (!existingUser?.emailVerified) return false

            // 双身份验证
            if (existingUser.isTwoFactorEnable) {
                const twoFactorConfirmation =
                    await getTwoFactorConfirmationByUserId(existingUser.id)
                if (!twoFactorConfirmation) return false
                // delete two factor confirmation for next sign in
                await db.twoFactorConfirmation.delete({
                    where: {id: twoFactorConfirmation.id}
                })
                return true
            }

            return true
        },
        async jwt({token, user, profile}) {
            // token里的sub就是user的id
            // console.log(token)
            // undefined
            // console.log(user)
            // token.customField = 'test'

            if (!token.sub) {
                return token
            }

            const existingUser = await getUserById(token.sub)
            if (!existingUser) return token

            // account保存第三方的登录信息
            const existingAccount = await getAccountByUserId(
                existingUser.id
            )

            // !! 转为boolean
            token.isOAuth = !!existingAccount
            token.role = existingUser.role
            token.email = existingUser.email
            token.name = existingUser.name
            token.isTwoFactorEnable = existingUser.isTwoFactorEnable

            return token
        },
        async session({token, session}) {
            // if (session.user) {
            //     session.user.customField = token.customField
            // }

            // 转移token里的sub(userid)到session
            if (token.sub && session.user) {
                session.user.id = token.sub
            }
            if (token.role && session.user) {
                session.user.role = token.role as UserRole
                // session.user.role = token.role as 'ADMIN' | 'USER'
            }
            if (session.user) {
                session.user.isTwoFactorEnable = token.isTwoFactorEnable as boolean
            }
            if (session.user) {
                session.user.name = token.name!
                session.user.email = token.email!
                session.user.isOAuth = token.isOAuth as boolean
            }

            return session
        }
    },
    adapter: PrismaAdapter(db),
    session: {
        strategy: 'jwt'
    },
    ...authOptions
})